/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */

package l1j.server.server.clientpackets;
import l1j.opqlo.NewSystem.各項記錄輸出;
import l1j.opqlo.Server.L1World.L1World;

import java.sql.Timestamp;//TODO 記錄文件檔 by 阿傑

import l1j.server.echo.ClientThread;
import l1j.server.server.datatables.PetTypeTable;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.L1Object;
import l1j.server.server.model.L1PcInventory;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.Instance.L1PetInstance;
import l1j.server.server.model.Instance.L1SummonInstance;
import l1j.server.server.serverpackets.S_ItemName;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.templates.L1Item;
import l1j.server.server.templates.L1Npc;
import l1j.server.server.templates.L1PetType;
import l1j.server.server.utils.Random;

import java.util.logging.Level;
import java.util.logging.Logger;
/**
 * 處理收到由客戶端傳來給道具的封包
 */
public class C_GiveItem extends ClientBasePacket {
	private static final String C_GIVE_ITEM = "[C] C_GiveItem";
	private static final Logger _log = Logger.getLogger(C_GiveItem.class.getName());
	/*
	private void usePetWeaponArmor(final L1NpcInstance target,final  L1ItemInstance item) {
		if (!(target instanceof L1PetInstance)) {
			return;
		}
		L1PetInstance pet = (L1PetInstance) target;
		L1PetItem petItem = PetItemTable.getInstance().getTemplate(
				item.getItemId());
		if (petItem.getUseType() == 1) { // 牙齒
			pet.usePetWeapon(pet, item);
		} else if (petItem.getUseType() == 0) { // 盔甲
			pet.usePetArmor(pet, item);
		}
	}
	 */
	private final static String receivableImpls[] = new String[] { "L1Npc", // NPC
		"L1Monster", // モンスター
		"L1Guardian", // エルフの森の守護者
		"L1Teleporter", // テレポーター
	"L1Guard" }; // ガード
	private void evolvePet(final L1PcInstance pc, final L1NpcInstance target) {
		if (!(target instanceof L1PetInstance)) {
			return;
		}
		final L1PcInventory inv = pc.getInventory();
		final L1PetInstance pet = (L1PetInstance) target;
		final L1ItemInstance petamu = inv.getItem(pet.getItemObjId());
		if (pet.getLevel() >= 30 && // Lv30以上
				pc == pet.getMaster() && // 自分のペット
				petamu != null) {
			final L1ItemInstance highpetamu = inv.storeItem(40316, 1);
			if (highpetamu != null) {
				pet.evolvePet( // 進化させる
						highpetamu.getId());
				pc.sendPackets(new S_ItemName(highpetamu));
				inv.removeItem(petamu, 1);
			}
		}
	}

	/*
	private void eatFood(final L1PcInstance pc,final  L1NpcInstance target,
			final L1ItemInstance item, final int count) {
		if (!(target instanceof L1PetInstance)) {
			return;
		}
		final L1PetInstance pet = (L1PetInstance) target;
		final L1Pet _l1pet = PetTable.getInstance().getTemplate(item.getId());
		int food = 0;
		int foodCount = 0;
		boolean isFull = false;

		if (pet.get_food() == 100) { // 非常飽
			return;
		}
		// 食物營養度判斷
		if (item.getItem().getFoodVolume() != 0) {
			// 吃掉食物的數量判斷
			for (int i = 0; i < count; i++) {
				food = item.getItem().getFoodVolume() / 10;
				food += pet.get_food();
				if (!isFull) {
					if (food >= 100) {
						isFull = true;
						pet.set_food(100);
						foodCount++;
					} else {
						pet.set_food(food);
						foodCount++;
					}
				} else {
					break;
				}
			}
			if (foodCount != 0) {
				pet.getInventory().consumeItem(item.getItemId(), foodCount); // 吃掉食物
				// 紀錄寵物飽食度
				_l1pet.set_food(pet.get_food());
				PetTable.getInstance().storePetFood(_l1pet);
			}
		}
	}*/
	@Override
	public String getType() {
		return C_GIVE_ITEM;
	}

	private boolean isNpcItemReceivable(final L1Npc npc) {
		for (final String impl : receivableImpls) {
			if (npc.getImpl().equals(impl)) {
				return true;
			}
		}
		return false;
	}

	private boolean isTamePet(final L1NpcInstance npc) {
		boolean isSuccess = false;
		final int npcId = npc.getNpcTemplate().get_npcId();
		if (npcId == 45313) { // タイガー
			if (npc.getMaxHp() / 3 > npc.getCurrentHp() // HPが1/3未満で1/16の確率
					&& Random.nextInt(16) == 15) {
				isSuccess = true;
			}
		} else {
			if (npc.getMaxHp() / 3 > npc.getCurrentHp()) {
				isSuccess = true;
			}
		}

		if (npcId == 45313 || npcId == 45044 || npcId == 45711) { // タイガー、ラクーン、紀州犬の子犬
			if (npc.isResurrect()) { // RES後はテイム不可
				isSuccess = false;
			}
		}

		return isSuccess;
	}

	@Override
	public void start(final byte[] decrypt, final ClientThread client) {
		try {
			// 資料載入
			this.read(decrypt);

			final L1PcInstance pc = client.getActiveChar();
			if (pc == null || pc.isGhost()) {
				return;
			}

			final int targetId = this.readD();
			this.readH();
			this.readH();
			final int itemId = this.readD();
			int count = this.readD();
			//opqlo 防洗
			count = Math.abs(count);
			count = Math.min(count,2000000000);
			//opqlo 防洗


			final L1Object object = L1World.getInstance().findObject(targetId);
			if (object == null || !(object instanceof L1NpcInstance)) {
				return;
			}
			final L1NpcInstance target = (L1NpcInstance) object;
			if (!this.isNpcItemReceivable(target.getNpcTemplate())) {
				return;
			}

			final L1Inventory inv = pc.getInventory();
			L1ItemInstance item = inv.getItem(itemId);
			if (item == null) {
				return;
			}
			final L1Item itemTable = item.getItem();
			if(!pc.isGm()){
				if(itemTable.getType2() != 0 // 只有道具可以給予
						|| itemTable.getDelete_Date() !=null //opqlo 道具天數刪除系統(無法給予)
						|| itemTable.isTradable() == false // \f1%0%d是不可轉移的…
						|| item.getBless() >= 128 // 封印的裝備
						|| item.getItemId() == 90308 // opqlo 商城元寶不可丟給怪物
						){
					pc.sendPackets(new S_ServerMessage(210, item.getItem().getName()));
					return;
				}else if (item.isEquipped()) {
					pc.sendPackets(new S_ServerMessage(141)); // \f1你不能夠將轉移已經裝備的物品
					return;
				}
			}
			 if(pc.getDollList().getDollByItem(item.getId()) !=null){//TODO 魔法娃娃使用判斷無法給予
					pc.sendPackets(new S_ServerMessage(1181));
					return;
				}
			// 使用中的寵物項鍊 - 無法給予
			for (final L1NpcInstance petNpc : pc.getPetList().values()) {
				if (petNpc instanceof L1PetInstance) {
					final L1PetInstance pet = (L1PetInstance) petNpc;
					if (item.getId() == pet.getItemObjId()) {
						// \f1%0は捨てたりまたは他人に讓ることができません。
						pc.sendPackets(new S_ServerMessage(210, item.getItem().getName()));
						return;
					}
				}
			}

			//TODO 魔法娃娃使用判斷無法給予
			/*	for (final L1DollInstance doll : pc.getDollList().values()) {
				if (doll.getItemObjId() == item.getId()) {
					pc.sendPackets(new S_ServerMessage(1181));
					return;
				}
			}*/


			final L1Inventory targetInv = target.getInventory();
			if (targetInv.checkAddItem(item, count) != L1Inventory.OK) {
				pc.sendPackets(new S_ServerMessage(942)); // 相手のアイテムが重すぎるため、これ以上あげられません。
				return;
			}
			StringBuilder log = new StringBuilder();
			log.append("IP(").append(pc.getNetConnection().getIp().toString()).append(")	玩家:【").append(pc.getName()).append("】的【")
			.append(item.getViewName()).append("】		數量:").append(count).append("流水號:").append(item.getId()).append(" 道具丟給	").append(target.getName()).append("	時間:(").append( new Timestamp(System.currentTimeMillis())).append(")。");
			各項記錄輸出.LogSave(28, log.toString());
			log.delete(0, log.length());
			log = null;

			item = inv.tradeItem(item, count, targetInv);
			target.onGetItem(item);
			target.turnOnOffLight();
			pc.turnOnOffLight();
			final L1PetType petType = PetTypeTable.getInstance().get(target.getNpcTemplate().get_npcId());
			if (petType == null || target.isDead()) {
				return;
			}
			// 捕抓寵物
			if (item.getItemId() == petType.getItemIdForTaming()) {
				this.tamePet(pc, target);

				// 進化寵物
			}else if (item.getItemId() == petType.getEvolvItemId() && petType.canEvolve()) {//TODO 寵物進化必須物品DB化
				this.evolvePet(pc, target);
			}
			/*if (item.getItem().getType2() == 0) { // 道具類
				// 食物類
				if (item.getItem().getType() == 7) {
					eatFood(pc, target, item, count);
				}
				// 寵物裝備類
				else if ((item.getItem().getType() == 11)
						&& (petType.canUseEquipment())) { // 判斷是否可用寵物裝備
					usePetWeaponArmor(target, item);
				}
			}*/
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);

		} finally {
			this.over();
		}
	}
	private void tamePet(final L1PcInstance pc,final  L1NpcInstance target) {
		if (target instanceof L1PetInstance
				|| target instanceof L1SummonInstance) {
			return;
		}

		int petcost = 0;
		final Object[] petlist = pc.getPetList().values().toArray();
		for (final Object pet : petlist) {
			petcost += ((L1NpcInstance) pet).getPetcost();
		}
		int charisma = pc.getCha();
		if (pc.isCrown()) { // 君主
			charisma += 6;
		} else if (pc.isElf()) { // エルフ
			charisma += 12;
		} else if (pc.isWizard()) { // WIZ
			charisma += 6;
		} else if (pc.isDarkelf()) { // DE
			charisma += 6;
		} else if (pc.isDragonKnight()) { // ドラゴンナイト
			charisma += 6;
		} else if (pc.isIllusionist()) { // イリュージョニスト
			charisma += 6;
		}
		charisma -= petcost;
		final int npcId = target.getNpcId();
		int divisor = 6;//TODO 修正寵物召換笛
		int petCount = 0;//TODO 修正寵物召換笛
		if (npcId == 45313 || npcId == 45710 // タイガー、バトルタイガー
				|| npcId == 45711 || npcId == 45712) { // 紀州犬の子犬、紀州犬
			divisor = 12;
		} else {
			divisor = 6;
		}
		petCount = charisma / divisor;
		if (petCount <= 0) {
			pc.sendPackets(new S_ServerMessage(489)); // 引き取ろうとするペットが多すぎます。
			return;
		}
		final L1PcInventory inv = pc.getInventory();
		if (inv.getSize() < 180) {
			if (this.isTamePet(target)) {
				final L1ItemInstance petamu = inv.storeItem(40314, 1); // ペットのアミュレット
				if (petamu != null) {
					new L1PetInstance(target, pc, petamu.getId());
					pc.sendPackets(new S_ItemName(petamu));
				}
			} else {
				pc.sendPackets(new S_ServerMessage(324)); // てなずけるのに失敗しました。
			}
		}
	}
}
